<template>
  <DialPlate>
    <template v-slot:time-left>
      <SettingCircleButton />
    </template>
    <template v-slot:time-box>
      <div class="time" :style="{ color: configStore.config.color }">{{ formattedTime }}</div>
      <div class="date" v-if="configStore.config.isShowDate" :style="{ color: configStore.config.color }">{{ formattedDate }}</div>
    </template>
    <template v-slot:time-right>
      <ChangeCircleButton routerUrl="/timer/stopwatch" />
    </template>
  </DialPlate>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import DialPlate from '@renderer/components/dialPlate/DialPlate.vue'
import SettingCircleButton from '@renderer/components/button/SettingCircleButton.vue'
import ChangeCircleButton from '@renderer/components/button/ChangeCircleButton.vue'
import { useConfigStore } from '@renderer/stores/configStore';

const configStore = useConfigStore()

// 获取当前时间
const currentTime = ref(new Date())

// 设置定时器，每200毫秒更新一次时间
const timer = ref<NodeJS.Timeout | null>(null)

// 格式化数字，不足两位前面补0
const formatNumber = (num) => num.toString().padStart(2, '0')

// 获取当前日期
const weekDays = ['日', '一', '二', '三', '四', '五', '六']

// 格式化时间
const formattedTime = computed(() => {
  const hours = formatNumber(currentTime.value.getHours())
  const minutes = formatNumber(currentTime.value.getMinutes())
  const seconds = formatNumber(currentTime.value.getSeconds())
  return `${hours}:${minutes}:${seconds}`
})

// 格式化日期
const formattedDate = computed(() => {
  const year = currentTime.value.getFullYear()
  const month = currentTime.value.getMonth() + 1
  const date = currentTime.value.getDate()
  const day = weekDays[currentTime.value.getDay()]
  return `${year}/${month}/${date} ${day}`
})


onMounted(() => {
  // 初始化时间
  timer.value = setInterval(() => {
    currentTime.value = new Date()
  }, 200)
})

onBeforeUnmount(() => {
  // 清除定时器
  if(timer.value) {
    clearInterval(timer.value as NodeJS.Timeout)
  }
  timer.value = null
})
</script>

<style lang="scss" scoped>
@font-face {
  font-family: 'Inconicso-Bold';
  src: url('../assets/font/Inconsolata-Bold-3.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
  font-display: swap;
  /* 避免渲染阻塞 */
}

.time {
  font-size: 24px;
  line-height: 1.2;
  font-family: 'Inconicso-Bold', monospace;
}

.date {
  font-size: 10px;
  line-height: 1.2;
  font-family: 'Inconicso-Bold', monospace;
  white-space: nowrap;
}
</style>
